﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Forms;


namespace FiveStone
{
    public class MySocket
    {
        #region 属性、私有变量
        private static Thread mythread;
        private static TcpListener tlTcpListen;//tcp监听实例
        private static NetworkStream nsStream;
        private static StreamReader srRead;//
        private static StreamWriter swWriter;
        /// <summary>
        /// tcp连接是否成功
        /// </summary>
        public static bool tcpConnect = false;
        /// <summary>
        /// tcp监听是否成功！
        /// </summary>
        public static bool tcpListen = false;
        private static string myname;
        private static string hename;

        private static string _Port;
        /// <summary>
        /// 监听和发送端口号
        /// </summary>
        public static string Port
        {
            get { return _Port; }
            set { _Port = value; }
        }
        private static string _IP;
        /// <summary>
        /// IP地址
        /// </summary>
        public static string IP
        {
            get { return _IP; }
            set { _IP = value; }
        }
        #endregion
        
        #region 发送TCP
        private static void TcpSend()
        {
            IPAddress ipRemote;
            try
            {
                ipRemote = IPAddress.Parse(IP);
            }
            catch //判断给定的IP地址的合法性
            {
                MessageBox.Show("输入的IP地址不合法！", "错误提示！");
                return;
            }

            IPHostEntry ipHost;
            try
            {
                ipHost = Dns.Resolve(IP);
            }
            catch //判断IP地址对应主机是否在线
            {
                MessageBox.Show("远程主机不在线！", "错误提示！");                
                return;
            }

            string sHostName = ipHost.HostName;
            try
            {
                TcpClient tcpClient = new TcpClient(sHostName, int.Parse(Port));//对远程主机的8000端口提出TCP连接申请
                nsStream = tcpClient.GetStream();//通过申请，并获取传送数据的网络基础数据流
                swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例                
                tcpConnect = true;                
            }
            catch
            {
                MessageBox.Show("无法和远程主机"+Port+"端口建立连接！", "错误提示！");
                return;
            }
        }

        public static void TcpSend(string smessage)
        {
            try
            {
                if(!tcpConnect)
                    TcpSend();
                swWriter.WriteLine(smessage);//刷新当前数据流中的数据
                swWriter.Flush();
            }
            catch
            {
                MessageBox.Show("发送数据包出错！");
            }
        }

        public static void StopSend()
        {
            try
            {
                if (tcpConnect)
                {
                    nsStream.Close();
                    swWriter.Close();//释放资源
                    tcpConnect = false;
                }
            }
            catch
            {
            }
        }
        #endregion

        #region 监听tcp port
        public static void TcpListen()
        {
            try
            {
                bool blistener = true;
                tlTcpListen = new TcpListener(int.Parse(Port)); //以8000端口号来初始化TcpListener实例
                tlTcpListen.Start(); //开始监听
                TcpClient tcClient = tlTcpListen.AcceptTcpClient(); //通过TCP连接请求
                nsStream = tcClient.GetStream(); //获取用以发送、接收数据的网络基础数据流
                srRead = new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例                
                tcpListen = true;
                while (blistener) //循环侦听
                {
                    string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据
                    if (sMessage == "STOP") //判断是否为断开TCP连接控制码
                    {
                        tlTcpListen.Stop(); //关闭侦听
                        nsStream.Close(); //释放资源
                        srRead.Close();
                        mythread.Abort(); //中止线程
                        return;
                    }
                    //MessageBox.Show(sMessage, "tcp");
                    
                    //string sTime = DateTime.Now.ToShortTimeString(); //获取接收数据时的时间
                    //listBox1.Items.Add(sTime + " " + sMessage);
                }
            }
            catch (System.Security.SecurityException)
            {
                MessageBox.Show("侦听失败！", "错误");
            }
        }

        public static void RunTcpListen()
        {
            mythread = new Thread(MySocket.TcpListen);
            mythread.Start();
        }

        public static void StopTcpListen()
        {
            try
            {
                tlTcpListen.Stop(); //关闭侦听
                if(nsStream!=null)
                    nsStream.Close();
                if(srRead!=null)
                    srRead.Close();//释放资源
                mythread.Abort();
                tcpListen = false;
            }
            catch
            {
            }
        }
        #endregion

        /// <summary> 获取本机IP</summary><returns></returns>
        public static IPAddress GetServerIP()
        {
            IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddr = ipHost.AddressList[0];
            return ipAddr;
        }

        #region old socket
        //private static Socket socket;

        

        ///// <summary>
        ///// 等待接收参数
        ///// </summary>
        //public static void BeginListen()
        //{            
        //    IPAddress ServerIp = GetServerIP();
        //    IPEndPoint iep = new IPEndPoint(ServerIp, int.Parse(Port));
        //    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    byte[] byteMessage = new byte[100];
        //    socket.Bind(iep);
        //    try
        //    {
        //        socket.Listen(5);
        //        Socket newSocket = socket.Accept();
        //        newSocket.Receive(byteMessage);                
        //        string msg = Encoding.Default.GetString(byteMessage);
        //        System.Windows.Forms.MessageBox.Show(msg, "信息");
        //    }
        //    catch (SocketException Ex)
        //    {

        //    }            

        //}


        //public static void BeginSend(string strSend)
        //{
        //    IPAddress serverIp = IPAddress.Parse(IP);
        //    int serverPort = Convert.ToInt32(Port);
        //    IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
        //    byte[] byteMessage;
        //    Socket socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    socketSend.Connect(iep);
        //    byteMessage = Encoding.ASCII.GetBytes(strSend);
        //    socketSend.Send(byteMessage);
        //    socketSend.Shutdown(SocketShutdown.Both);
        //    socketSend.Close();
        //}

        #endregion    
    }
}
